<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElLoading } from 'element-plus';
import { Plus, Delete, RefreshRight } from '@element-plus/icons-vue';
import { TravelNoteApi } from '@/api/new/travelNoteApi.js';

// 定义props和emits
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['close']);

// 识别类型
const recognitionTypes = [
  { id: 'animal', name: '动物识别' },
  { id: 'plant', name: '植物识别' }
];

const activeType = ref('animal');
const uploadedImage = ref(null);
const recognitionResults = ref([]);
const isRecognizing = ref(false);
const uploadRef = ref(null);
const dialogContentRef = ref(null); // 引用对话框内容

// 切换识别类型
const switchType = (typeId) => {
  activeType.value = typeId;
  if (uploadedImage.value) {
    performRecognition();
  }
};

// 上传图片
const handleUpload = async (file) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  
  // 文件大小验证
  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过5MB');
    return false;
  }
  
  try {
    const loading = ElLoading.service({
      target: dialogContentRef.value, // 将 loading 绑定到对话框内容
      lock: true,
      text: '正在上传图片...',
      background: 'rgba(255, 255, 255, 0.8)' // 设置为白色蒙板
    });
    
    // 使用TravelNoteApi.uploadImage上传图片
    const imageUrl = await TravelNoteApi.uploadImage(file);
    
    uploadedImage.value = imageUrl;
    
    loading.close();
    
    // 上传成功后执行识别
    performRecognition();
  } catch (error) {
    ElMessage.error(`上传失败: ${error.message || '未知错误'}`);
    console.error('上传图片失败:', error);
  }
  
  return false;
};

// 删除图片
const removeImage = () => {
  uploadedImage.value = null;
  recognitionResults.value = [];
};

// 重新识别
const retryRecognition = () => {
  if (uploadedImage.value) {
    performRecognition();
  }
};

// 执行识别
const performRecognition = async () => {
  if (!uploadedImage.value) return;
  
  isRecognizing.value = true;
  const loading = ElLoading.service({
    target: dialogContentRef.value, // 将 loading 绑定到对话框内容
    lock: true,
    text: '正在识别中...',
    background: 'rgba(255, 255, 255, 0.8)' // 设置为白色蒙板
  });
  
  try {
    const response = await TravelNoteApi.detectImage(uploadedImage.value, activeType.value);
    const result = typeof response === 'string' ? JSON.parse(response) : response;
    
    if (result && result.result) {
      recognitionResults.value = result.result.map(item => ({
        name: item.name,
        confidence: parseFloat(item.score)
      }));
      
      console.log('识别结果:', recognitionResults.value);
      ElMessage.success('识别成功!');
    } else {
      throw new Error('识别结果为空');
    }
  } catch (error) {
    console.error('识别失败:', error);
    ElMessage.error(`识别失败: ${error.message || '未知错误'}`);
    recognitionResults.value = [];
  } finally {
    loading.close();
    isRecognizing.value = false;
  }
};

// 关闭对话框
const closeDialog = () => {
  emit('close');
};

// 触发上传
const triggerUpload = () => {
  uploadRef.value.click();
};
</script>

<template>
  <div class="ai-recognition-dialog">
    <div class="dialog-overlay" @click="closeDialog"></div>
    <div class="dialog-content" ref="dialogContentRef">
      <div class="dialog-header">
        <h2>AI智能识别</h2>
        <button class="close-btn" @click="closeDialog">×</button>
      </div>
      
      <div class="dialog-body">
        <div class="recognition-content">
          <el-card shadow="hover" class="upload-section">
            <div 
              class="upload-area" 
              :class="{ 'has-image': uploadedImage }"
              @click="triggerUpload"
            >
              <template v-if="!uploadedImage">
                <Plus class="upload-icon" />
                <p>点击上传图片</p>
                <p class="upload-hint">支持jpg、png、jpeg格式</p>
              </template>
              <img v-else :src="uploadedImage" class="preview-image" />
              
              <input 
                ref="uploadRef"
                type="file" 
                accept="image/*" 
                style="display: none"
                @change="(e) => handleUpload(e.target.files[0])"
              />
            </div>
            
            <div class="upload-actions" v-if="uploadedImage">
              <el-button type="danger" icon="Delete" @click="removeImage">删除</el-button>
              <el-button type="primary" icon="RefreshRight" @click="retryRecognition">重新识别</el-button>
            </div>
          </el-card>
          
          <el-card shadow="hover" class="result-section">
            <div class="recognition-results" v-if="recognitionResults.length > 0">
              <h3>识别结果</h3>
              <div class="result-item" v-for="(result, index) in recognitionResults" :key="index">
                <div class="result-header">
                  <div class="result-name">{{ result.name }}</div>
                  <div class="result-score">{{ (result.confidence * 100).toFixed(2) }}%</div>
                </div>
                <el-progress :percentage="result.confidence * 100" :show-text="false" />
              </div>
            </div>
            <div v-else class="result-placeholder">
              <p>识别结果将在这里显示</p>
            </div>
          </el-card>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.ai-recognition-dialog {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.dialog-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

.dialog-content {
  position: relative;
  width: 90%;
  max-width: 1000px;
  max-height: 90vh;
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  animation: fadeIn 0.3s ease-out;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #eee;
}

.dialog-header h2 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.dialog-body {
  padding: 20px;
  overflow-y: auto;
  flex: 1;
  display: flex;
  gap: 20px;
}

.recognition-content {
  display: flex;
  gap: 20px;
  width: 100%;
}

.upload-section, .result-section {
  flex: 1;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  overflow-y: auto;
  max-height: 400px;
}

.upload-section:hover, .result-section:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.upload-area {
  width: 100%;
  height: 300px;
  border: 2px dashed #ddd;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
  overflow: hidden;
}

.upload-area:hover {
  border-color: #409eff;
}

.upload-icon {
  font-size: 48px;
  color: #ddd;
  margin-bottom: 12px;
}

.upload-area p {
  margin: 4px 0;
  color: #666;
}

.upload-hint {
  font-size: 12px;
  color: #999;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.upload-actions {
  display: flex;
  gap: 12px;
  margin-top: 10px;
}

.result-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
}

.recognition-results {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 16px;
  overflow-y: auto;
  max-height: 400px;
}

.recognition-results h3 {
  margin-top: 0;
  margin-bottom: 12px;
  font-size: 16px;
  color: #333;
}

.result-item {
  margin-bottom: 12px;
  padding-bottom: 12px;
  border-bottom: 1px solid #eee;
}

.result-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;
}

.result-name {
  font-weight: bold;
  font-size: 16px;
}

.result-score {
  color: #409eff;
  font-weight: 500;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: scale(0.9);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

@media (max-width: 768px) {
  .recognition-content {
    flex-direction: column;
  }
}
</style>